package sensors;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * A service which provides many sensors service such as touchSensor,
 * soundSensor ,lightSensor and UltrasanicSensor.and we can figure out its values.
 * @author Chengqiang Sun
 * @version 1.0.0.0
 * @since 2012.08.01
 */
public class SensorServiceImpl implements SensorService{

	//get the distance to object in front of the LEJO
	public int getDistanceToObject()
	{
		int temp = 0;
		byte[] data=new byte[]{0,0,0,0,0};
		try {
			Socket socket = new Socket("localhost", 8778);
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			dis.read(data, 0, 5);
			dis.close();
			dis = null;
			socket.close();
			socket = null;
			temp = data[0];
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	}
	
	//get the brightness value through the lightSensor
	public int getBrightness() {
		int temp = 0;
		byte[] data=new byte[]{0,0,0,0,0};
		try {
			Socket socket = new Socket("localhost", 8778);
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			dis.read(data, 0, 5);
			dis.close();
			dis = null;
			socket.close();
			socket = null;
			temp = data[2];
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	} 

	//get the soundValue through the soundSensor
	public int getSoundValue() {
		int temp = 0;
		byte[] data=new byte[]{0,0,0,0,0};
		try {
			Socket socket = new Socket("localhost", 8778);
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			dis.read(data, 0, 5);
			dis.close();
			dis = null;
			socket.close();
			socket = null;
			temp = data[3];
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	}
	
	//get the touchSensor value ,true represents touched while false represents untouched
	public boolean checkTouched(){
		int temp = 0;
		boolean flag = false;
		byte[] data=new byte[]{0,0,0,0,0};
		try {
			Socket socket = new Socket("localhost", 8778);
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			dis.read(data, 0, 5);
			dis.close();
			dis = null;
			socket.close();
			socket = null;
			temp = data[4];
			if (temp == 1) {
				flag = true;
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

}
